package org.viettan.android.main.xml;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.List;

import org.viettan.android.main.io.UrlUtility;
import org.viettan.android.main.model.RadioEpisode;
import org.viettan.android.main.model.RadioProgram;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;

import com.google.common.collect.Lists;

/**
 * Handles parsing of {@link RadioEpisode}-related XML.
 */
public class RadioEpisodeXmlParser {

    /**
     * Parses an XML source for {@link RadioProgram} including their individual {@link RadioEpisode}
     * s.
     *
     * @param xml
     * @return list of {@link RadioProgram} populated with all its {@link RadioEpisode}s.
     * @throws XmlPullParserException
     * @throws IOException
     */
    public List<RadioProgram> parse(String xml) throws XmlPullParserException, IOException {

	// create XML parser
	XmlPullParser parser = XmlPullParserFactory.newInstance().newPullParser();
	parser.setInput(new ByteArrayInputStream(xml.getBytes()), null);

	// create result objects
	List<RadioProgram> radioPrograms = Lists.newArrayList();
	RadioProgram currentRadioProgram = null;
	RadioEpisode currentRadioEpisode = null;

	// parse each tag one at time
	int eventType = parser.getEventType();
	while (eventType != XmlPullParser.END_DOCUMENT) {
	    eventType = parser.next();
	    if (eventType != XmlPullParser.START_TAG)
		continue;

	    String tagName = parser.getName();
	    if (tagName.equalsIgnoreCase("title")) {
		if (currentRadioEpisode == null) {
		    // this happens because this is the title of the <channel> tag
		    continue;
		}
		currentRadioEpisode.setTitle(parser.nextText().trim());
	    } else if (tagName.equalsIgnoreCase("mp3")) {
		currentRadioEpisode.setMp3Url(UrlUtility.parseUrl(parser.nextText()));
	    } else if (tagName.equalsIgnoreCase("author")) {
		currentRadioEpisode.setAuthor(parser.nextText());
	    } else if (tagName.equalsIgnoreCase("program")) {
		// create new program
		currentRadioProgram = new RadioProgram()
			.setId(Integer.parseInt(parser.getAttributeValue(null, "idart")))
			.setTitle(parser.getAttributeValue(null, "title"));
		radioPrograms.add(currentRadioProgram);
	    } else if (tagName.equalsIgnoreCase("item")) {
		// create a new episode
		currentRadioEpisode = new RadioEpisode()
			.setId(Integer.parseInt(parser.getAttributeValue(null, "idart")))
			.setSubtitle(parser.getAttributeValue(null, "subtitle"));
		currentRadioProgram.addEpisode(currentRadioEpisode);
	    }
	}
	return radioPrograms;
    }
}
